/*
 * Copyright © 2018 CODESTD.COM Inc. All rights reserved.
 */
package com.codestd.security.controller;

import com.codestd.security.base.ResponseBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录控制器
 *
 * @author jaune
 * @since 1.0.0
 */
@RestController
public class LoginController {

    @PostMapping("/login")
    public ResponseBean login(HttpServletRequest request) {
        String errorClassName = (String)request.getAttribute(
                FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);

        if (errorClassName != null) {
            errorClassName = errorClassName.substring(errorClassName.lastIndexOf(".") + 1);
        } else {
            return new ResponseBean();
        }
        String errorMessage;
        switch (errorClassName) {
            case "IncorrectCredentialsException":
                errorMessage = "密码错误！";
                break;
            case "UnknownAccountException":
                errorMessage = "用户名不存在！";
                break;
            case "DisabledAccountException":
                errorMessage = "账户已被禁用！";
                break;
            case "LockedAccountException":
                errorMessage = "账户已被锁定！";
                break;
            default:
                errorMessage = "登录失败！";
        }
        return ResponseBean.builder().success(false)
                .message(errorMessage)
                .build();
    }

    /**
     * 注销
     */
    @GetMapping("/logout")
    public void logout() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
    }

}
